package guoanmaker.personal.business.service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.transaction.Transactional;

import org.springframework.stereotype.Service;

import guoanmaker.personal.business.model.PersonalUser;
import guoanmaker.personal.business.model.ReturnResult;
import guoanmaker.personal.business.repository.PersonalUserRepository;
import guoanmaker.personal.helper.common.abstractobj.ApiController;
import guoanmaker.personal.helper.common.util.SMSHelper;

@Service
public class ThirdpartLoginService {
	@Resource
	private PersonalUserRepository personalUserRepository;
	
	
	
	//网页端发送验证码接口
	@Transactional
	public ReturnResult  sendMsg(String telephone){
		ReturnResult returnResult = new ReturnResult();

		String url = ApiController.SMS_URL;
		String username = ApiController.SMS_USERNAME;
		String password = ApiController.SMS_PASSWORD;
		String epid = ApiController.SMS_EPID;

		String param = "";
		StringBuilder code = new StringBuilder();
		Random random = new Random();
		// 生成6位验证码
		for (int i = 0; i < 6; i++) {
			code.append(String.valueOf(random.nextInt(10)));
		}
		
		String smsText = "" + code;
		List<PersonalUser>   users=personalUserRepository.findUserByUsername(telephone);
		if(users.size()>0){
			returnResult.setKey("error");
    		returnResult.setValue("手机号注册过请用原来的手机号");
    		return returnResult;
		}
		
		try {
			param = "username=" + username + "&password=" + password + "&phone=" + telephone + "&epid=" + epid
					+ "&linkid=&subcode=" + "&message=" + URLEncoder.encode("验证码为:", "gb2312") + smsText;
			String result = SMSHelper.SendGET(url, param);
			if(result.equals("00")){
				returnResult.setKey("success");
	    		returnResult.setValue(smsText);
			}else if(result.equals("2")){
					returnResult.setKey("error");
		    		returnResult.setValue("鉴权失败");
			}else{
					returnResult.setKey("error");
		    		returnResult.setValue("发送失败");
			}
			
		} catch (UnsupportedEncodingException e) {
			returnResult.setKey("error");
    		returnResult.setValue("发送失败");
		}
		
		return returnResult;
    }

		

	

}
